﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Objects;

namespace Dao
{
    public class JCCD_Dao
    {
        /// <summary>
        /// 新增一条记录
        /// </summary>
        /// <param name="entity">记录实体</param>
        /// <returns>操作影响的行数</returns>
        public int Add(JCCD entity)
        {
            using (var context = new Dao.ErpEntities())
            {
                context.JCCDSet.AddObject(entity);
                return context.SaveChanges();
            }
        }

        /// <summary>
        /// 更新一条记录
        /// </summary>
        /// <param name="entity">记录实体</param>
        /// <returns>操作影响的行数</returns>
        public int Update(JCCD entity)
        {
            using (var context = new Dao.ErpEntities())
            {
                JCCD entity2 = context.JCCDSet.FirstOrDefault(c => c.ID == entity.ID);
                if (entity2 != null)
                {
                    //entity2 = entity;
                    context.JCCDSet.ApplyCurrentValues(entity);
                    return context.SaveChanges();
                }
                return 0;
            }
        }

        /// <summary>
        /// 删除一条记录
        /// </summary>
        /// <param name="id">记录Id</param>
        /// <returns>操作影响的行数</returns>
        public int Delete(string id)
        {
            using (var context = new Dao.ErpEntities())
            {
                Guid guid = Guid.Parse(id);
                JCCD entity = context.JCCDSet.FirstOrDefault(c => c.ID == guid);
                if (entity != null)
                {
                    context.DeleteObject(entity);
                    return context.SaveChanges();
                }
                return 0;
            }
        }

        /// <summary>
        /// 查询一条记录
        /// </summary>
        /// <param name="id">记录Id</param>
        /// <returns>查询结果实体</returns>
        public JCCD Query(string id)
        {
            using (var context = new Dao.ErpEntities())
            {
                Guid guid = Guid.Parse(id);
                JCCD entity = context.JCCDSet.FirstOrDefault(c => c.ID == guid);
                return entity;
            }
        }

        /// <summary>
        /// 查询所有记录
        /// </summary>
        /// <returns>查询结果集</returns>
        public List<JCCD> QueryAll()
        {
            using (var context = new Dao.ErpEntities())
            {
                var q = from c in context.JCCDSet
                        select c;
                List<JCCD> list = new List<JCCD>();
                if (q.Count() > 0)
                {
                    foreach (var c in q)
                    {
                        list.Add(c);
                    }
                }
                return list;
            }
        }


        public List<vJCCD> QueryAllEx()
        {
            using (var context = new Dao.ErpEntities())
            {
                var q = from c in context.vJCCDSet
                        select c;
                List<vJCCD> list = new List<vJCCD>();
                if (q.Count() > 0)
                {
                    foreach (var c in q)
                    {
                        list.Add(c);
                    }
                }
                return list;
            }
        }

        public List<JCCD> QueryJCDBySql(string departmentId, string userId, string cgyId, string datetimeStart, string datetimeEnd)
        {
            return QueryBySql("0001", departmentId, userId, cgyId, datetimeStart, datetimeEnd);
        }

        public List<JCCD> QueryCCDBySql(string departmentId, string userId, string cgyId, string datetimeStart, string datetimeEnd)
        {
            return QueryBySql("1001", departmentId, userId, cgyId, datetimeStart, datetimeEnd);
        }

        /// <summary>
        /// TODO 用存储过程提高效率
        /// 查询所有记录
        /// </summary>
        /// <returns>查询结果集</returns>
        public List<JCCD> QueryBySql(string lx, string departmentId, string userId, string cgyId, string datetimeStart, string datetimeEnd)
        {
            List<JCCD> list = new List<JCCD>();
            using (var context = new Dao.ErpEntities())
            {
                var q = from j in context.JCCDSet
                        where j.LX == lx
                        select j;

                if (!string.IsNullOrEmpty(departmentId) && (!"0".Equals(departmentId)))
                {
                    Guid did = Guid.Parse(departmentId);
                    q = q.Where(c => c.BMID == did);
                }

                if (!string.IsNullOrEmpty(userId) && (!"0".Equals(userId)))
                {
                    Guid uid = Guid.Parse(userId);
                    q = q.Where(c => c.RYID == uid);
                }

                if (!string.IsNullOrEmpty(cgyId) && (!"0".Equals(cgyId)))
                {
                    Guid cuid = Guid.Parse(cgyId);
                    q = q.Where(c => c.CGYID == cuid);
                }

                if ((!string.IsNullOrEmpty(datetimeStart)) && (!"0".Equals(datetimeStart)))
                {
                    DateTime start = DateTime.Parse(datetimeStart);
                    q = q.Where(c => (c.RQ >= start));
                }

                if ((!string.IsNullOrEmpty(datetimeEnd)) && (!"0".Equals(datetimeEnd)))
                {
                    DateTime end = DateTime.Parse(datetimeEnd);
                    q = q.Where(c => (c.RQ <= end));
                }

                q = q.OrderByDescending(c => c.RQ);

                foreach (JCCD c in q)
                {
                    list.Add(c);
                }
           
                return list;
            }
        }

        public List<vJCCD> QueryJCDBySqlEx(string departmentId, string userId, string cgyId, string datetimeStart, string datetimeEnd)
        {
            return QueryBySqlEx("0001", departmentId, userId, cgyId, datetimeStart, datetimeEnd);
        }

        public List<vJCCD> QueryCCDBySqlEx(string departmentId, string userId, string cgyId, string datetimeStart, string datetimeEnd)
        {
            return QueryBySqlEx("1001", departmentId, userId, cgyId, datetimeStart, datetimeEnd);
        }

        public List<vJCCD> QueryBySqlEx(string lx, string departmentId, string userId, string cgyId, string datetimeStart, string datetimeEnd)
        {
            List<vJCCD> list = new List<vJCCD>();
            using (var context = new Dao.ErpEntities())
            {
                var q = from j in context.vJCCDSet
                        where j.LX == lx
                        select j;

                if (!string.IsNullOrEmpty(departmentId) && (!"0".Equals(departmentId)))
                {
                    Guid did = Guid.Parse(departmentId);
                    q = q.Where(c => c.BMID == did);
                }

                if (!string.IsNullOrEmpty(userId) && (!"0".Equals(userId)))
                {
                    Guid uid = Guid.Parse(userId);
                    q = q.Where(c => c.RYID == uid);
                }

                if (!string.IsNullOrEmpty(cgyId) && (!"0".Equals(cgyId)))
                {
                    Guid cuid = Guid.Parse(cgyId);
                    q = q.Where(c => c.CGYID == cuid);
                }

                if ((!string.IsNullOrEmpty(datetimeStart)) && (!"0".Equals(datetimeStart)))
                {
                    DateTime start = DateTime.Parse(datetimeStart);
                    q = q.Where(c => (c.RQ >= start));
                }

                if ((!string.IsNullOrEmpty(datetimeEnd)) && (!"0".Equals(datetimeEnd)))
                {
                    DateTime end = DateTime.Parse(datetimeEnd);
                    q = q.Where(c => (c.RQ <= end));
                }

                q = q.OrderByDescending(c => c.RQ);

                foreach (vJCCD c in q)
                {
                    list.Add(c);
                }

                return list;
            }
        }

        public List<JCCD> QueryBy(string bh, string bm, string ry)
        {
            List<JCCD> list = new List<JCCD>();
            using (var context = new Dao.ErpEntities())
            {
                ObjectQuery<JCCD> q = context.CreateQuery<JCCD>("select value c from JCCD as c");
                if (!bh.Trim().Equals(string.Empty))
                {
                    q = q.Where("c.LX=@lx");
                }
                ObjectResult<JCCD> results = q.Execute(MergeOption.NoTracking);
                foreach (JCCD c in results)
                {
                    list.Add(c);
                }

                return list;
            }
        }

        public bool ConfirmIn(string id)
        {
            bool res = false;

            using (var context = new Dao.ErpEntities())
            {
                Guid guid = Guid.Parse(id);
                JCCD entity = context.JCCDSet.Include("JCCDMXB").FirstOrDefault(c => c.ID == guid);
                List<Guid> wpids = new List<Guid>();
                foreach (var mxb in entity.JCCDMXB)
                {
                    wpids.Add(mxb.WPID);
                }

                // 取所有库存中有的明细表中的物料，如果有则加数量
                var q = from wp in context.KCSet
                         where wpids.Contains(wp.WPID)
                         select wp;

                foreach (var wp in q)
                {
                    wp.SL += entity.JCCDMXB.FirstOrDefault(c => c.WPID == wp.WPID).SL;
                    wpids.Remove(wp.WPID);
                }

                // 库存表中没有的物料，新增库存记录
                foreach (Guid wpid in wpids)
                {
                    JCCDMXB mxb = entity.JCCDMXB.FirstOrDefault(c => c.WPID == wpid);
                    KC kc = new KC()
                    {
                        ID = Guid.NewGuid(),
                        WPID = wpid,
                        WPLX = mxb.WPLX,
                        CKID = mxb.CKID,
                        CWID = mxb.CWID,
                        SL = mxb.SL,
                        ZXDJ = mxb.DJ,
                        DW = mxb.DWBH
                    };
                    context.KCSet.AddObject(kc);
                }

                entity.ZT = 1;
                context.JCCDSet.ApplyCurrentValues(entity);
                res = context.SaveChanges() > 1;
            }

            return res;
        }

        public bool ConfirmOut(string id, ref List<Guid> lessList)
        {
            bool res = false;

            using (var context = new Dao.ErpEntities())
            {
                Guid guid = Guid.Parse(id);
                JCCD entity = context.JCCDSet.Include("JCCDMXB").FirstOrDefault(c => c.ID == guid);
                List<Guid> wpids = new List<Guid>();
                foreach (var mxb in entity.JCCDMXB) 
                {
                    wpids.Add(mxb.WPID);
                }

                // 取所有库存中有的明细表中的物料，如果有则减数量
                //    将数量不足的记录下来
                List<Guid> lessIds = new List<Guid>();
                var q = from wp in context.KCSet
                        where wpids.Contains(wp.WPID)
                        select wp;

                foreach (var wp in q)
                {
                    wp.SL -= entity.JCCDMXB.FirstOrDefault(c => c.WPID == wp.WPID).SL;
                    wpids.Remove(wp.WPID);
                    if (wp.SL < 0)
                    {
                        lessIds.Add(wp.WPID);
                    }
                }

                if (lessIds.Count > 0)
                {
                    res = false;
                    lessList = lessIds;
                    return res;
                }

                foreach (Guid wpid in wpids)
                {
                    JCCDMXB mxb = entity.JCCDMXB.FirstOrDefault(c => c.WPID == wpid);
                    KC kc = new KC()
                    {
                        ID = Guid.NewGuid(),
                        WPID = wpid,
                        WPLX = mxb.WPLX,
                        CKID = mxb.CKID,
                        CWID = mxb.CWID,
                        SL = mxb.SL,
                        ZXDJ = mxb.DJ,
                        DW = mxb.DWBH
                    };
                    context.KCSet.AddObject(kc);
                }

                entity.ZT = 1;
                context.JCCDSet.ApplyCurrentValues(entity);
                res = context.SaveChanges() > 1;
            }

            return res;
        }
    }
}
